package other.edan.intlpass.campaign;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.Campaign;
import com.rkhd.platform.sdk.data.model.InvitingClients__c;
import com.rkhd.platform.sdk.exception.CustomConfigException;
import com.rkhd.platform.sdk.exception.EmailException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.EmailAttachment;
import com.rkhd.platform.sdk.model.EmailBody;
import com.rkhd.platform.sdk.service.CustomConfigService;
import com.rkhd.platform.sdk.service.EmailService;
import org.apache.commons.lang.StringUtils;
import other.edan.intlpass.entity.Email;
import other.edan.intlpass.utils.HCXObjectService;
import other.edan.intlpass.utils.Result;
import other.edan.intlpass.utils.SendEmailUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 发送市场活动附件到客户的邮件
 * @Author: 黎炎松
 * @Date: 2024/8/20 17:48
 */
@RestApi(baseUrl = "/campaign")
public class SendCampaignEmail implements ApprovalEvent {
    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "发送市场活动附件客户的邮件 ==> ";

    /**
     * 手动发送市场活动邮件
     * @param dataId
     * @return
     */
    @RestMapping(value = "/sendEmail", method = RequestMethod.POST)
    public Result sendEmail(@RestQueryParam(name = "id") Long dataId) {
        LOGGER.info(LOGGER_MSG + "执行了按钮事件 = " + dataId);
        return sendEmailToAccount(dataId);
    }

    /**
     * 审批触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public ApprovalEventResponse execute(ApprovalEventRequest request) throws ScriptBusinessException {
        LOGGER.info(LOGGER_MSG + "审批触发事件");
        sendEmailToAccount(request.getDataId());

        ApprovalEventResponse response = new ApprovalEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        return response;
    }

    public static void main(String[] args) {
        new SendCampaignEmail().sendEmailToAccount(3598953061371808L);
    }

    /**
     * 发送附件到客户邮箱
     * @param campaignId
     * @return
     */
    public Result sendEmailToAccount(Long campaignId) {
        LOGGER.info(LOGGER_MSG + "处理开始: " + campaignId);
        try {
            // 获取市场活动的数据
            String sql = "select id,campaignName,emailDeliveryContent__c,emailInvitationAttachment__c from campaign where id = " + campaignId;
            JSONArray jsonArray = HCXObjectService.queryAllUseXoql(sql);
            JSONObject campaign = jsonArray.getJSONObject(0);
            LOGGER.info(LOGGER_MSG + "campaign: " + campaign);
            List<JSONObject> fileList = JSONArray.parseArray(campaign.getString("emailInvitationAttachment__c"), JSONObject.class);
            if(fileList == null || fileList.size() <= 0) {
                LOGGER.error(LOGGER_MSG + "市场活动附件不可为空");
                return Result.error("The market activity attachment cannot be empty");
            }

            // 邮件发送内容
            String emailDeliveryContent = campaign.getString("emailDeliveryContent__c");
            System.out.println(emailDeliveryContent);
            if (StringUtils.isBlank(emailDeliveryContent)) {
                LOGGER.error(LOGGER_MSG + "邮件发送内容不可为空");
                return Result.error("The email content cannot be empty");
            }
            emailDeliveryContent = emailDeliveryContent.replaceAll(" ", "&nbsp;"); // 转换空格
            emailDeliveryContent = emailDeliveryContent.replaceAll("\n", "<br />"); // 转换换行

            // 获取客户的邮箱
            sql = String.format("select id,sendStatus__c,accounts__c.customerEmail__c email from invitingClients__c where (sendStatus__c != 2 or sendStatus__c is null) and campaign__c = %s ", campaignId);
            jsonArray = HCXObjectService.queryAllUseXoql(sql);
            if (jsonArray.size() <= 0) {
                LOGGER.error(LOGGER_MSG + "需要发送客户列表为空，无需处理");
                return Result.error("The customer list to be sent is empty. No action is required");
            }

            // 获取客户邮箱
            List<JSONObject> invitingClientsList = jsonArray.toJavaList(JSONObject.class);
            List<String> emailList = invitingClientsList.stream().filter(v -> StringUtils.isNotBlank(v.getString("email"))).map(v -> v.getString("email")).distinct().collect(Collectors.toList());
            LOGGER.info(LOGGER_MSG + "emailList: " + emailList);

            // 获取发送数据
            LOGGER.info(LOGGER_MSG + "发送邮件");
            String campaignName = campaign.getString("campaignName");
            List<EmailAttachment> sendFileList = fileList.stream().map(v -> new EmailAttachment(v.getString("name"), v.getString("url"))).collect(Collectors.toList());
            Email email = new Email();
            email.setSubject(campaignName); // 主题
            email.setContent(emailDeliveryContent); // 内容
            email.setReceiverList(emailList); // 收件人列表
            email.setAttachmentList(sendFileList); // 附件
            SendEmailUtils.sendEmail(email);

            // 更新邀约客户的发送状态
            List<InvitingClients__c> crmUpList = invitingClientsList.stream().map(v -> {
                InvitingClients__c upInvitingClients = new InvitingClients__c();
                upInvitingClients.setId(v.getLong("id"));
                upInvitingClients.setSendStatus__c(2);
                return upInvitingClients;
            }).collect(Collectors.toList());
            HCXObjectService.updateBatch(crmUpList);

            LOGGER.info(LOGGER_MSG + "发送邮件成功");
            return Result.success();
        } catch (Exception e) {
            LOGGER.error(LOGGER_MSG + "发送邮件异常: " + e.getMessage());
            return Result.error("Sending email exception: " + e.getMessage());
        }
    }

}

